<?php

namespace App\Http\Controllers\Admin;

use App\Admin\Form;
use App\Admin\Grid;
use App\Admin\Grid\Displayers\Actions;
use App\Admin\Layout\Content;
use App\Admin\Traits\ModelForm;
use App\Models\Lotto;
use App\Models\LottoPlayer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LottoController extends Controller
{
    use ModelForm;

    public function index()
    {
        return \Admin::content(function (Content $content) {
            $content->header('抽奖');
            $content->description('所有抽奖');
            $content->body($this->grid()->render());
        });
    }

    protected function grid()
    {
        return Lotto::grid(function (Grid $grid) {
            $grid->model()->with('players');

            $grid->id('编号')->sortable();

            $grid->title('标题')->editable();
            $grid->valid('是否开启')->switch();
            $grid->column('players_count', '参与人数')->display(function () {
                return count($this->players);
            });
            $grid->column('winner_count', '中奖人数')->display(function () {
                return count(array_filter($this->players, function ($p) {
                    return $p['pivot']['award'];
                }));
            });

            $grid->actions(function (Actions $actions) {
                $showLink = route('lottos.show', ['lotto' => $actions->row->id]);
                $viewPlayerLink = route('admin.lotto-players.index', ['lotto[title]' => $actions->row->title]);
                $actions->prepend('<a href="'.$viewPlayerLink.'" class="layui-btn layui-btn-xs">参与人员</a>');
                $actions->prepend('<a target="_blank" href="'.$showLink.'" class="layui-btn layui-btn-xs">查看</a>');
            });

            $grid->created_at('添加时间');
        });
    }

    public function create()
    {
        return \Admin::content(function (Content $content) {
            $content->header('抽奖');
            $content->description('添加抽奖');
            $content->row($this->form());
        });
    }

    public function edit($id)
    {
        return \Admin::content(function (Content $content) use ($id) {
            $content->header('抽奖');
            $content->description('编辑抽奖');
            $content->row($this->form()->edit($id));
        });
    }

    protected function form()
    {
        Form::extend('lottos', \App\AdminFields\Lottos::class);

        return Lotto::form(function (Form $form) {
            $form->display('id', '编号');

            $form->text('title', '标题');
            $form->switch('valid', '是否启用');
            $form->file('bg_image', '背景图')->maxSize('5mb')->ext('jpg,png,jpeg,gif');
            $form->file('bg_music', '背景音乐')->maxSize('5mb')->dir('music')->ext('mp3');

            $form->lottos('settings', '设置');

            $form->display('created_at', '添加时间');
            $form->display('updated_at', '更新时间');
        });
    }
}
